<?php
if (Yii::app()->request->isAjaxRequest) {
    Yii::app()->clientscript->scriptMap['jquery.js'] = false;
    Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
    Yii::app()->clientscript->scriptMap['jquery.yiigridview.js'] = false;
}
?>

<script>
    $(document).ready(function () {
        $( "input:submit").button();
        <?php if($this->getCredit()==0 && $this->getDebit()==0) : ?>
        //$("#accountingvouchers-form").find("#transactionmasternarration").prop('disabled', true);
        //$("#accountingvouchers-form").find("#transactionmasternarration").attr('readOnly', 'readonly');
        $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").attr('readOnly', 'readonly');
        $("#Transactionmaster_transactioncrdr").focus();
        <?php endif; ?>
            
        <?php if($this->getCredit()>0 && $this->getDebit()>0 && $this->getCredit()==$this->getDebit()) : ?>
        //$("#accountingvouchers-form").find("#transactionmasternarration").prop('disabled', true);
        //$("#accountingvouchers-form").find("#transactionmasternarration").attr('readOnly', 'readonly');
        //$("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").attr('readOnly', 'readonly');
        $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").focus();
        <?php endif; ?>
            
        
            
//        $("#Transactionmaster_acledger").focusout(function() {
//            $("#Transactionmaster_acledger").val("-");
//            $("#Transactionmaster_acledger").val("");
//        });
    });
//        $.ajax({
//          url: "index.php?r=transactionmaster/initrow",
//          success: function(data){
//                            $.fn.yiiGridView.update("transaction-grid", {
//                                data: $(this).serialize()
//                            });                        
//          }
//        });



function validateAccountingVoucher(){
//    if($("#Transactionmaster_transactioncrdr").val() !='' && $("#Transactionmaster_acledger").val() !='' && $("#Transactionmaster_transactionamount").val()!=''){
    $.ajax({
        url: "<?php echo $this->createUrl('transactionmaster/validateAccountingVoucher'); ?>",
        type: "POST",
        dataType: "json",
        data: jQuery("#accountingvouchers-form").serialize(),
        error: function(xhr, textStatus, errorThrown){
            //alert("Error..."); 
            return false();
        },
        success: function (data) {
            return true;
        }
    });    
//    }
}

function accountingvouchersFormSubmit(){
    $("#accountingvouchers-form-submit").click();
}

function saveAccountingVoucher(option){
//    if($("#Transactionmaster_transactioncrdr").val() !='' && $("#Transactionmaster_acledger").val() !='' && $("#Transactionmaster_transactionamount").val()!=''){
    $.ajax({
        url: "<?php echo $this->createUrl('transactionmaster/addrow'); ?>",
        type: "POST",
        dataType: "json",
        data: jQuery("#accountingvouchers-form").serialize(),
        error: function(xhr, textStatus, errorThrown){
//            alert("Error1... " + textStatus + errorThrown); return false();
            alert("Error...");
//            alert($.parseJSON(xhr));
        },
        success: function (data) {
//            alert("succ11..." + data.status); 
            $.fn.yiiGridView.update("transaction-grid", {
                //data: $(obj).serialize()
            });
            if(option == 'clear'){
                window.credit = data.credit;
                window.debit = data.debit;
                if(!(data.credit > 0 && data.debit > 0 && data.credit == data.debit)){                
                    $("#Transactionmaster_transactioncrdr").focus(); 
                }
                $("#id").val("-1");
                $('#accountingvouchers-form')[0].reset();
//                $("#Transactionmaster_transactioncrdr").val("");
//                $("#Transactionmaster_acledger").val("");
//                $("#Transactionmaster_transactionamount").val("");
            }
            if(data.credit > 0 && data.debit > 0 && data.credit == data.debit){                
                //$("#accountingvouchers-form").find("#transactionmasternarration").prop('disabled', false);
                $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").removeAttr('readOnly');
                $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").focus();
                //alert(data.credit + " - " + data.debit);
            }
            else{
        //        $("#accountingvouchers-form").find("#transactionmasternarration").prop('disabled', true);
                $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").attr('readOnly', 'readonly');
            }

//        if($('#id').val()>=0){
//            $('#transaction-grid_c0_' + $('#id').val()).attr('checked', true);
//        }

        return true;
        }
    });    
//    }
}


function ajaxSubmit(option){
//    if($("#Transactionmaster_transactioncrdr").val() !='' && $("#Transactionmaster_acledger").val() !='' && $("#Transactionmaster_transactionamount").val()!=''){
    $.ajax({
        url: "<?php echo $this->createUrl('transactionmaster/addrow'); ?>",
        type: "POST",
        dataType: "json",
        data: jQuery("#accountingvouchers-form").serialize(),
        error: function(xhr, textStatus, errorThrown){
//            alert("Error...");
//            alert($.parseJSON(xhr));
        },
        success: function (data) {
            $.fn.yiiGridView.update("transaction-grid", {
                //data: $(obj).serialize()
            });
            if(option == 'clear'){
                window.credit = data.credit;
                window.debit = data.debit;
                if(!(data.credit > 0 && data.debit > 0 && data.credit == data.debit)){                
                    $("#Transactionmaster_transactioncrdr").focus(); 
                }
                $("#id").val("-1");
                $("#Transactionmaster_transactioncrdr").val("");
                $("#Transactionmaster_acledger").val("");
                $("#Transactionmaster_transactionamount").val("");
            }
            if(data.credit > 0 && data.debit > 0 && data.credit == data.debit){                
                //$("#accountingvouchers-form").find("#transactionmasternarration").prop('disabled', false);
                $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").removeAttr('readOnly');
                $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").focus();
            }
            else{
        //        $("#accountingvouchers-form").find("#transactionmasternarration").prop('disabled', true);
                $("#accountingvouchers-form").find("#Transactionmaster_transactionmasternarration").attr('readOnly', 'readonly');
            }

//        if($('#id').val()>=0){
//            $('#transaction-grid_c0_' + $('#id').val()).attr('checked', true);
//        }

        return true;
        }
    });    
//    }
}
</script>

<style>
    .grid-view table{
        border: none;
    }
</style>

<?php
//    Yii::app()->clientscript->scriptMap['jquery.js'] = false;
//    Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;

        //Yii::app()->clientscript->scriptMap['jquery.yiigridview.js'] = true;
//    echo $model->idvouchertype . ' - ' . $transactionmaster->idtransactionmaster . ' - ' . $transactionmaster->idvouchertype;

?>


<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'accountingvouchers-form',
	'enableAjaxValidation'=>true,
        'action' => $this->createUrl('transactionmaster/createAccountingVoucher')    
)); ?>

	<?php echo $form->errorSummary($model); ?>
    
    <style>
        .divrow{
            clear: both;
        }
        .divrow div{
/*            width: 50%;*/
            display: block;
            float: left;
        }
        .divrow div div{
/*            float: none;*/
        }
    </style>
    <div class="divrow">
        <div class="row" style="width: 23%;"> 
                <?php echo $form->labelEx($model,'transactioncrdr'); ?>            
		<?php 
                    $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
                        'model'=>$model,
                        'attribute'=>'transactioncrdr',
//                        'id'=>'transactioncrdr',
                        'theme' => 'bgscstpc',
                        'source'=>array('CR', 'DR'),
                            'htmlOptions' => array(
                         ),
                        'options'=>array(
                            'showAnim'=>'fold',
                            'change'=>'js:function(event, ui) {
                                $("#Transactionmaster_acledger").val("");

                                //ajaxSubmit(""); 
//                                validateAccountingVoucher();
                                return true;
                             }'
                        ),
                        'htmlOptions' => array(                            
                        )
                        
                    ));
                    ?>
		<?php echo $form->error($model,'transactioncrdr', array('style' => 'float:none;')); ?>
	</div>
        
        <div class="row" style="width: 23%;"> 
                <?php echo $form->labelEx($model,'acledger'); ?>            
                <?php
                    $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
                        'model' => $model, 
//                        'name'=>'acledger',
                        'attribute'=>'acledger',
//                        'id'=>'acledger',
                        //'id' => 'Acledger_acgroupname',
                        'theme' => 'bgscstpc',
                        //'source' => $this->createUrl('transactionmaster/autocompleteAcledger', array('type' => $type)),
                        'source'=>'js: function(request, response) {
                            $.ajax({
                                url: "'.$this->createUrl('transactionmaster/autocompleteAcledger').'",
                                dataType: "json",
                                data: {
                                    term: request.term,
                                    type: "'.$type.'",
                                    transactioncrdr: $("#Transactionmaster_transactioncrdr").val()
                                },
                                success: function (data) {
                                        response(data);
                                },
                            })
                         }',
                        
                        // additional javascript options for the autocomplete plugin
                        'options'=>array(
                            'showAnim'=>'fold',
                            'change'=>'js:function(event, ui) {
                                //alert("change"); 
//                                if(this.value == ""){
//                                    this.value = "-";
//                                    this.value = "";
//                                }
//                                ajaxSubmit(""); 
                                //validateAccountingVoucher();
                                return true;
                             }',
                            'create'=>'js:function(event, ui) {
//                                this.value = "-";
//                                this.value = "";
                                //$("#Transactionmaster_acledger") = "-";
                                //$("#Transactionmaster_acledger") = "";
                                //alert("create"); 
                             }',
                            
                        ),
                        'htmlOptions' => array(  
                            'onblur' => '
                                    if(this.value == ""){
//                                        alert($(this).parent().attr("class"));
                                  //      $(this).parent().attr("class", "row error");
                                    }
                                ',
                        )
                    ));
                ?>
		<?php echo $form->error($model,'acledger', array('style' => 'float:none;')); ?>
	</div>

        <div class="row" style="width: 23%;"> 
                <?php echo $form->labelEx($model,'transactionamount'); ?>            
		<?php 
                    echo CHTML::activeTextField(
                            $model,
                            'transactionamount',
                            $htmlOptions = array(
                                'rows'=>6, 
                                'cols'=>50,
                                'onchange'=>'
//                                    validateAccountingVoucher();
//                                    saveAccountingVoucher("clear");
//                                    ajaxSubmit("clear");                                    
                                 ',
                                    

//                                    $.ajax({
//                                      url: "index.php?r=transactionmaster/addrow",
////                                      type:"POST",
//                                        data: {
//                                            id: $("#id").val()
//                                            transactioncrdr: $("#Transactionmaster_transactioncrdr").val()
//                                        },                                      
//                                      success: function( data ) {
//                                        alert(data);
////                                        $.fn.yiiGridView.update(\"transaction-grid\", {
////                                            data: $(this).serialize()
////                                        });
////                                        $(\"#Transactionmaster_transactioncrdr\").focus();
////                                        $(\"#id\").val(\"-1\");
////                                        $(\"#Transactionmaster_transactioncrdr\").val(\"\");
////                                        $(\"#Transactionmaster_acledger\").val(\"\");
////                                        $(\"#transactionamount\").val(\"\");
//
//                                        return true;
//                                      }
//                                    });'
                            )
                    ); 
                ?>
		<?php echo $form->error($model,'transactionamount'); ?>
       </div>
        
        <div class="row" style="width: 31%;"> 
            <span style="float: right">
                <?php echo $form->labelEx($model,'transactionmasternarration'); ?>
		<?php //echo $form->textField($model,'transactionmasternarration',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo $form->textArea($model,'transactionmasternarration',array('rows'=>3, 'cols'=>50)); ?>
                <?php
                    //echo CHTML::textArea("transactionmasternarration", $transactionmaster->transactionmasternarration, array('rows'=>3, 'cols'=>50))
                ?>
		<?php echo $form->error($model,'transactionmasternarration'); ?>
            </span>
      </div>
    </div>        
	<?php echo CHTML::hiddenField('id', '-1'); ?>
	<?php echo CHTML::hiddenField('idtransactionmaster', $transactionmaster->idtransactionmaster); ?>
	<?php echo CHTML::hiddenField('idvouchertype', $model->idvouchertype); ?>
	<?php //echo $form->textField($model,'idvouchertype'); ?>

       
        <div id="gridcontainer">
            <?php 
            $columns = array(
		array(
                    'class'=>'CCheckBoxColumn',
                    'footerHtmlOptions' => array('style' => 'border: none;'),
		),                
                array(
                    'name' => 'id',
//                    'value' => 'CHtml::textField("transactiondetails[" . $data[\'id\'] . "][id]", $data[\'id\'], array(\'width\'=>20,\'size\'=>7,\'maxlength\'=>30,\'style\'=>\'text-align:right\'))',
                    'value'=>'$data[\'id\']', 
                    'type' => 'raw',
                    'footerHtmlOptions' => array('style' => 'border: none;'),
                    'htmlOptions' => array('style' => 'display:none;'),                    
                    'headerHtmlOptions' => array('style' => 'display:none'),
                    'footerHtmlOptions' => array('style' => 'display:none'),
                ),
                array(
                    'name' => 'transactioncrdr',      
                    'type' => 'raw',
                    'value'=>'$data[\'transactioncrdr\']', 
                    'htmlOptions' => array('style' => 'width:10%;'),
                    'headerHtmlOptions' => array('style' => 'width:10%;'),
                    'footerHtmlOptions' => array('style' => 'border: none;width:10%;'),
                ),
                array(
                    'name' => 'acledger',      
                    'type' => 'raw',
                    'value'=>'$data[\'acledger\']', 
                    'htmlOptions' => array('style' => 'width:60%;'),
                    'headerHtmlOptions' => array('style' => 'width:60%;'),
                    'footerHtmlOptions' => array('style' => 'border: none;width:60%;'),
                ),
                array(
                    'name' => 'debit',      
                    'type' => 'raw',
                    'value'=>'$data[\'debit\']', 
                    'footer'=> $this->getDebit(),
                    'htmlOptions' => array('style' => 'text-align:right;width:15%;'),
                    'headerHtmlOptions' => array('style' => 'width:15%;'),
                    'footerHtmlOptions' => array('style' => 'text-align:right;font-weight:bold;width:15%;border-width: 4px; border-style: double; border-right: none; border-left: none; border-top: none;'),
                ),
                array(
                    'name' => 'credit',      
                    'type' => 'text',
                    'value'=>'$data[\'credit\']', 
                    'footer'=> $this->getCredit(),
                    'htmlOptions' => array('style' => 'text-align:right;width:15%;'),
                    'headerHtmlOptions' => array('style' => 'width:15%;'),
                    'footerHtmlOptions' => array('style' => 'text-align:right;font-weight:bold;width:15%;border-width: 4px; border-style: double; border-right: none; border-left: none; border-top: none;'),
                ),
                array(
                    'name' => 'transactionamount',      
                    'type' => 'raw',
                    'value'=>'$data[\'transactionamount\']', 
                    'htmlOptions' => array('style' => 'display:none;'),                    
                    'headerHtmlOptions' => array('style' => 'display:none'),
                    'footerHtmlOptions' => array('style' => 'display:none'),
                ),
        //    echo $form->dropDownList($model,'openingbalancecrdr',array('CR'=>'CR', 'DR'=>'DR'));        
            );
            
            $wid = $this->widget('ext.eziiui.widgets.grid.CGridViewUI', array(
//            $wid = $this->widget('ext.EDataTables.EDataTables', array(
                'id' => 'transaction-grid',
                'dataProvider' => $dataProvider,
                'columns' => $columns,
                //'enablePagination' => false,
                'summaryText' => '',
        //        'filter' => $filtersForm,
                'selectionChanged'=>'function(id){onSelectionChange()}',
                'beforeAjaxUpdate'=>'function(id, data){
                        //$("#Transactionmaster_transactioncrdr").focus();
                 }',
                'afterAjaxUpdate'=>'function(id, data){
                        if($("#id").val()>=0){                            
                            $("#transaction-grid_c0_" + $("#id").val()).attr("checked", true);
                            $("#transaction-grid_c0_" + $("#id").val()).parent().parent().attr("class", "selected ui-state-highlight");;
                        }
                    }'
            ));
            ?>            
        </div>
        
	<div class="row"> <!--transactiondetails -->
                <?php //echo $form->labelEx($model,'transactiondetails'); ?>            
		<?php //echo $form->textArea($model,'transactiondetails',array('rows'=>6, 'cols'=>50)); ?>
		<?php //echo $form->error($model,'transactiondetails'); ?>
	</div>
        
        
<script type="text/javascript">
    function onSelectionChange()
    {
            $('#accountingvouchers-form')[0].reset();
            var keys = $("#transaction-grid > div.keys > span");
            $("#id").val('-1');
//            $("#Transactionmaster_transactioncrdr").val('');
//            $("#Transactionmaster_acledger").val('');
//            $("#Transactionmaster_transactionamount").val('');
            var selectid = -1;
            $("#transaction-grid > table > tbody > tr").each(function(i)
            {
                    if($(this).hasClass("selected"))
                    {
                        $("#id").val($(this).children(":nth-child(2)").text());
                        selectid = $(this).children(":nth-child(2)").text();
                        $("#Transactionmaster_transactioncrdr").val($(this).children(":nth-child(3)").text());
                        $("#Transactionmaster_acledger").val($(this).children(":nth-child(4)").text());
                        $("#Transactionmaster_transactionamount").val($(this).children(":nth-child(7)").text());
                        //alert($("#id").val());

                        //alert($(this).children(":nth-child(2)").text());
    //                        $("#Pacjenci_patientNAME").val($(this).children(":nth-child(2)").text());
    //                        $("#Pacjenci_patientID").val(keys.eq(i).text());
                    }
                    else{
                        //$("#id").val('-1');                        
                    }
            });
//            alert(selectid);
            $("#transaction-grid_c0_" + selectid).prop("checked", true);

            
//            alert(window.credit + " " + window.debit);
            $("#Transactionmaster_transactioncrdr").focus();
    }    
function userClicks(target_id) {
        alert($.fn.yiiGridView.getSelection(target_id));
}
</script>        

        <div class="row buttons" style="text-align: right;">
		<?php echo CHtml::submitButton(Yii::t('application', 'Save'), $htmlOptions=array ('id' => 'accountingvouchers-form-submit' )); ?>
	</div>


        <?php
        ?>
        
<?php $this->endWidget(); ?>

</div><!-- form -->

<?php
$this->widget('ext.ajaxform.JAjaxForm', array(
    'formId' => 'accountingvouchers-form',
    'options' => array(
        'dataType' => 'json',
        'success' => 'js:function(data,statusText) { 
                    if(data.status == "Success"){
                        var index = $( "li", $tabs ).index( $( this ).parent() );
                        $tabs.tabs( "remove", index );
                        tabitems.splice( index, 1 );                    
                        $.fn.yiiGridView.update("transactionmaster-grid", {
                                data: $(this).serialize()
                        });
                    }
                    else{
                        $("#dialog-warning-msg").html(data.message); 
                        $("#dialog-warning").dialog("open"); 
                        $("#accountingvouchers-form")[0].reset();
                        $("#Transactionmaster_transactioncrdr").focus();                        
                        return false;
                    }
                    

//                    if(data.status == "Success"){
//                        $.fn.yiiGridView.update("transaction-grid", {
//                              data: $(this).serialize()
//                        });
//                        $("#dialog").dialog("close").destroy();
//                        return false;
//                    }
//                    else{
//                        $("#dialog-warning-msg").html("' . Yii::t('application', 'An error occurred while the form was being submitted.<br/>Please check your form data.') . '" + data.status); 
//                        $("#dialog-warning").dialog("open"); 
//                        return false;
//                    }
        }',
    ),
));

?>

<?php
$this->widget('zii.widgets.jui.CJuiButton', array(
    'buttonType'=>'button',
    'name'=>'btnClick',
    'caption'=>'Click',
    'theme' => 'bgscstpc',
    'options'=>array('icons'=>'js:{primary:"ui-icon-newwin"}'),
    'onclick'=>'js:function(){$("#accountingvouchers-form-submit").click(); return false;}',
));

echo CHtml::ajaxButton(
	'Test request',          // the link body (it will NOT be HTML-encoded.)
	'#', // the URL for the AJAX request. If empty, it is assumed to be the current URL.
	$htmlOptions = array(
		'onclick'=>'alert("Hello");'
	)
);
?>